<template>
  <div class="organization-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">{{ isSelectMode ? '选择付款对象' : rootDepartment.name }}</div>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <van-search
          v-model="searchValue"
          placeholder="搜索"
          shape="round"
          background="transparent"
          left-icon="search"
          @search="onSearch"
          @focus="onSearchFocus"
        />
      </div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item">{{ rootDepartment.name }}</span>
      <!-- 只有在非根部门时才显示箭头和当前部门 -->
      <template v-if="currentDepartment.id !== 'root'">
        <van-icon name="arrow" class="breadcrumb-arrow" />
        <span class="breadcrumb-item current">{{
          currentDepartment.name
        }}</span>
      </template>
    </div>

    <!-- 部门列表 -->
    <div class="department-list">
      <!-- 加载骨架屏 -->
      <div v-if="loading" class="org-skeleton">
        <van-skeleton :row="6" :loading="true" />
      </div>
      
      <!-- 部门列表 -->
      <div
        v-for="department in departments"
        :key="department.id"
        class="department-item"
        @click="enterDepartment(department)"
      >
        <div class="department-icon">
          <img src="@/assets/homeOther/organizational_icon.png" alt="部门" />
        </div>
        <div class="department-info">
          <div class="department-name">
            {{ department.name }}({{ department.memberCount }})
          </div>
        </div>
        <van-icon name="arrow" class="arrow-icon" />
      </div>
      
      <!-- 空状态 -->
      <!-- <div v-if="!loading && departments.length === 0" class="empty-container">
        <van-empty description="暂无部门数据" />
      </div> -->
    </div>
    <!-- 特殊用户信息区域 (CEO/HR) -->
    <div v-if="currentDepartment.id === 'root' && specialUsers.length > 0" class="boss-info" :class="{ 'no-departments': departments.length === 0 }">
      <div v-for="user in specialUsers" :key="user.id" class="boss-item" @click="isSelectMode ? selectUser(user) : null" :class="{ 'selectable': isSelectMode }">
        <div class="boss-avatar">
          <!-- <img :src="pictureOneImg" :alt="user.name" /> -->
           <AvatarDisplay :name="user.name" />
        </div>
        <div class="boss-details">
          <div class="boss-name"  @click="isSelectMode ? selectUser(user) : editUser(user.id)">
            {{ user.name }}
            <!-- <span v-if="user.ceo === 1" class="admin-tag">CEO</span> -->
            <!-- <span v-if="user.hr === 1" class="admin-tag">HR</span> -->
            <span v-if="user.admin === 1" class="admin-tag">管理员</span>
          </div>
          <div class="boss-position">{{ getUserPosition(user) }}</div>
          <!-- <div class="boss-phone">{{ user.phone }}</div> -->
        </div>
        <img
          v-if="!isSelectMode"
          src="/src/assets/homeOther/edit_icon.png"
          class="edit-icon"
          alt=""
          @click="editUser(user.id)"
        />
      </div>
    </div>
    
    <!-- 普通用户列表区域 -->
    <div v-if="currentDepartment.id === 'root' && shouldShowAllUsers" class="user-list">
      <!-- <div class="user-list-title">成员列表</div> -->
      <div v-for="user in userList" :key="user.id" class="user-item" @click="isSelectMode ? selectUser(user) : null" :class="{ 'selectable': isSelectMode }">
        <div class="user-avatar">
          <!-- <img :src="pictureOneImg" :alt="user.name" /> -->
            <AvatarDisplay :name="user.name" />
        </div>
        <div class="user-details">
          <div class="user-name"  @click="isSelectMode ? selectUser(user) : editUser(user.id)">
            {{ user.name }}
            <span v-if="user.admin === 1" class="admin-tag">管理员</span>
          </div>
          <div class="user-phone" >{{ getUserPosition(user) }}</div>
          <!-- <div class="user-phone">{{ user.phone }}</div> -->
        </div>
        <img
          v-if="!isSelectMode"
          src="/src/assets/homeOther/edit_icon.png"
          class="edit-icon"
          @click="editUser(user.id)"
          alt=""
        />
      </div>
    </div>
    <!-- 底部操作按钮 - 仅管理员可见且非选择模式 -->
    <div v-if="isAdmin && !isSelectMode" class="bottom-actions" :style="bottomActionsStyle">
      <div class="action-buttons">
        <div class="action-btn" @click="addMember">
          <span>添加成员</span>
        </div>
        <div class="action-btn" @click="addSubDepartment">
          <span>添加子部门</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast } from "vant";
import { getAllDepartments, type Department as ApiDepartment, type UserInfo } from "@/api/organization";
import { getUserById } from "@/api/user";
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue'
import { storage } from '@/utils/storage';
// 导入图片
import pictureOneImg from "@/assets/homeOther/sm_picture.png";

// 路由实例
const router = useRouter();
const route = useRoute();

// 是否为选择模式（从付款对象页面跳转过来）
const isSelectMode = computed(() => route.query.mode === 'select');
const selectSource = computed(() => route.query.from as string);

// 搜索值
const searchValue = ref("");

// 页面部门数据类型（适配前端显示需求）
interface Department {
  id: number;
  name: string;
  memberCount: number;
}

// 用户信息数据类型已从API导入

// 管理员信息数据类型
interface AdminInfo {
  name: string;
  position: string;
  avatar: string;
  phone: string;
  id: number;
}

// 根部门
const rootDepartment = reactive({
  id: "root",
  name: "北京君初律师事务所",
});

// 当前部门
const currentDepartment = reactive({
  id: "root",
  name: "北京君初律师事务所",
});

// 用户列表
const userList = ref<UserInfo[]>([]);

// 特殊用户列表 (CEO/HR)
const specialUsers = ref<UserInfo[]>([]);

// 是否显示所有用户
const shouldShowAllUsers = ref(false);

// 部门数据
const departments = ref<Department[]>([]);

// 加载状态 - 初始为false，避免闪烁
const loading = ref(false);

// 当前登录用户信息
const currentUser = ref<any>(null);
// 当前用户详细信息（从接口获取）
const currentUserDetail = ref<any>(null);

// 计算属性：判断当前用户是否为管理员
const isAdmin = computed(() => {
  console.log('isAdmin计算:', currentUserDetail.value);
  return currentUserDetail.value?.admin === 1;
});

// 底部按钮强制显示样式
const bottomActionsStyle = computed(() => ({
  position: 'fixed' as const,
  bottom: '0px',
  left: '0px',
  right: '0px',
  width: '100%',
  zIndex: 9999,
  display: 'block',
  visibility: 'visible' as const,
  opacity: 1
}));

// 返回上一页
const goBack = () => {
  router.back();
};

// 搜索功能
const onSearch = (value: string) => {
  // 跳转到搜索页面，传递搜索关键词
  router.push({
    path: '/organization/search',
    query: {
      keyword: value
    }
  });
};

// 搜索框获取焦点事件
const onSearchFocus = () => {
  // 跳转到搜索页面
  router.push('/organization/search');
};

// 进入部门详情
const enterDepartment = (department: Department) => {
  // 构建查询参数
  const query: any = {
    departmentName: department.name
  };
  
  // 如果是选择模式，传递选择模式参数
  if (isSelectMode.value) {
    query.mode = 'select';
    query.from = selectSource.value;
  }
  
  // 跳转到部门详情页面，传递部门ID和部门名称
  router.push({
    path: `/organization/department/${department.id}`,
    query
  });
};

// 添加成员
const addMember = () => {
  // 如果是在根组织页面，传递from=root参数
  console.log(departments.value,'-departments.value');
  //  departments为空的时候提示
  if(departments?.value?.length==0){
     showToast('暂无部门,请先添加子部门')
    return
  } 
  if (currentDepartment.id === 'root') {
    router.push('/organization/add-member?from=root');
  } else {
    // 如果是在部门页面，传递部门ID
    router.push(`/organization/add-member?from=department&departmentId=${currentDepartment.id}`);
  }
};

// 添加子部门
const addSubDepartment = () => {
  router.push('/organization/add-department?from=index&parentId=root');
};
// 获取部门数据
const fetchDepartments = async () => {
  try {
    loading.value = true;
    const response = await getAllDepartments();
    
    if (response.code === 0) {
      // 更新部门数据
      departments.value = response.data.departments.map(dept => ({
        id: dept.id,
        name: dept.name,
        memberCount: dept.num || 0, // 将num字段映射为memberCount，默认为0
      }));
      
      // 更新用户列表
      userList.value = response.data.userList || [];
      
      // 实现新的用户显示逻辑
      const ceoUsers = userList.value.filter(user => user.ceo === 1);
      const hrUsers = userList.value.filter(user => user.hr === 1);
      const adminUsers = userList.value.filter(user => user.admin === 1);
      
      // 检查是否同时存在CEO和HR用户
      const hasBothCeoAndHr = ceoUsers.length > 0 && hrUsers.length > 0;
      // 检查是否只有一个CEO或一个HR
      const hasOnlyCeoOrHr = (ceoUsers.length === 1 && hrUsers.length === 0) || (hrUsers.length === 1 && ceoUsers.length === 0);
      
      if (hasBothCeoAndHr) {
        // 同时存在CEO和HR时，只显示CEO、HR和管理员用户
        specialUsers.value = [...ceoUsers, ...hrUsers, ...adminUsers.filter(user => user.ceo !== 1 && user.hr !== 1)];
        shouldShowAllUsers.value = false;
      } else if (hasOnlyCeoOrHr) {
        // 只有一个CEO或一个HR时，显示所有用户
        specialUsers.value = [];
        shouldShowAllUsers.value = true;
      } else if (ceoUsers.length === 0 && hrUsers.length === 0) {
        // 没有CEO和HR时，显示所有用户
        specialUsers.value = [];
        shouldShowAllUsers.value = true;
      } else {
        // 其他情况（多个CEO或多个HR），只显示特殊用户
        specialUsers.value = [...ceoUsers, ...hrUsers, ...adminUsers.filter(user => user.ceo !== 1 && user.hr !== 1)];
        shouldShowAllUsers.value = false;
      }
      
      console.log('部门数据加载成功:', response.data);
      console.log('用户列表:', response.data.userList);
    } else {
      showToast(response.msg || '获取部门数据失败');
    }
  } catch (error) {
    console.error('获取部门数据失败:', error);
    showToast('获取部门数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 编辑用户信息
const editUser = (userId: number) => {
  if (userId) {
    router.push(`/organization/edit-member/${userId}?from=organization`);
  }
};

// 获取当前登录用户信息
const getCurrentUserInfo = async () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      currentUser.value = userInfo;
      console.log('当前用户信息:', userInfo);
      
      // 调用接口获取用户详细信息
      const response = await getUserById(userInfo.id.toString());
      if (response.code === 0) {
        currentUserDetail.value = response.data;
        console.log('用户详细信息:', response.data);
        console.log('是否为管理员:', response.data.admin === 1);
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 获取用户职位
const getUserPosition = (user: UserInfo) => {
  if (user.ceo === 1) return 'CEO';
  if (user.hr === 1) return '出纳';
  if (user.admin === 1) return '管理员';
  return '员工';
};

// 判断用户是否可以编辑
// const canEditUser = (user: UserInfo) => {
//   // CEO和HR用户不允许编辑
//   if (user.ceo === 1 || user.hr === 1) {
//     return false;
//   }
  
//   // 如果存在CEO和HR用户，管理员也不允许编辑
//   const hasCeoUsers = userList.value.some(u => u.ceo === 1);
//   const hasHrUsers = userList.value.some(u => u.hr === 1);
  
//   if (hasCeoUsers && hasHrUsers && user.admin === 1) {
//     return false;
//   }
  
//   return true;
// };

// 选择用户（选择模式下使用）
const selectUser = (user: UserInfo) => {
  if (!isSelectMode.value) return;
  
  // 根据来源页面返回不同的路径
  if (selectSource.value === 'payObject') {
    // 返回付款申请页面，携带选中的用户信息
    router.push({
      path: '/contract/addPay',
      query: {
        selectedUserId: user.id.toString(),
        selectedUserName: user.name
      }
    });
  }
};

// 页面加载
onMounted(async () => {
  console.log("组织架构页面已加载");
  
  // 优化加载体验：延迟显示loading，避免闪烁
  let loadingTimer: NodeJS.Timeout | null = null;
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    loading.value = true;
  }, 200);
  
  try {
    await getCurrentUserInfo(); // 获取当前用户信息
    fetchDepartments();
  } finally {
    // 数据加载完成后清除定时器和loading状态
    if (loadingTimer) {
      clearTimeout(loadingTimer);
      loadingTimer = null;
    }
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
@import url("./style/index.scss");

/* 选择模式下的样式 */
.selectable {
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: rgba(25, 137, 250, 0.05);
  }
  
  &:active {
    background-color: rgba(25, 137, 250, 0.1);
  }
}
</style>